package model

import (
	"log"
	"time"
)

type PageInstance struct {
	Limit  uint
	Offset uint
}

type Customer struct {
	Id         uint
	FirstName  string
	LastName   string
	Address1   string
	Address2   string
	Provine    string
	City       string
	Created_at time.Time
	Updated_at time.Time
	Deleted_at time.Time
	PageInstance
}
type PageData struct {
	FirstHref   string
	LastHref    string
	CurrentHref string
	UpHref      string
	DownHref    string
	CountEntry  uint
	PageInstance
}

func (p *PageData) New(pi *PageInstance) *PageData {

	row := DB.QueryRow("SELECT count(id) FROM customer")

	var count uint

	err := row.Scan(&count)

	if err != nil {
		log.Fatal(err)
	}

	return &PageData{
		FirstHref:   "first page",
		LastHref:    "last page",
		CurrentHref: "current page",
		UpHref:      "up page",
		DownHref:    "down page",
		CountEntry:       count,
		PageInstance: PageInstance{
			Limit:  pi.Limit,
			Offset: pi.Offset,
		},
	}

}

func (c *Customer) Add() bool {

	stmt, err := DB.Prepare("INSERT INTO customer (first_name, last_name, address1, address2, province, city, created_at, updated_at, deleted_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9);")

	if err != nil {
		log.Fatal(err)
	}

	_, err = stmt.Exec(c.FirstName, c.LastName, c.Address1, c.Address2, c.Provine, c.City, c.Created_at, c.Updated_at, c.Deleted_at)

	if err != nil {
		log.Fatal(err)
	}

	return true

}

func (c *Customer) GetOne() *Customer {

	row := DB.QueryRow("SELECT first_name, last_name, address1, address2, province, city, created_at, updated_at FROM customer WHERE id = $1", c.Id)

	err := row.Scan(&c.FirstName, &c.LastName, &c.Address1, &c.Address2, &c.Provine, &c.City, &c.Created_at, &c.Updated_at)

	if err != nil {
		log.Fatal(err)
	}

	return c
}

func (c *Customer) GetMany() []Customer {

	rows, err := DB.Query(`SELECT first_name, last_name, address1, address2,
	province, city, created_at, updated_at FROM customer
	LIMIT $1 OFFSET $2;`, c.Limit, c.Offset)

	if err != nil {
		log.Fatal(err)
	}

	customer := []Customer{}

	cr := Customer{}

	for rows.Next() {

		err = rows.Scan(&cr.FirstName, &cr.LastName, &cr.Address1, &cr.Address2, &cr.Provine, &cr.City, &cr.Created_at, &cr.Updated_at)

		if err != nil {
			log.Fatal(err)
		}

		customer = append(customer, cr)

	}

	return customer
}

func (c *Customer) Update() {

}

func (c *Customer) Delete() {

}
